<template>

  <el-dialog
    :visible.sync="dialogVisible"
    title="公告管理"
    width="50%"
    @close="handleClose">


    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="top">

      <el-form-item label="标题" prop="title">
        <el-input v-model="postForm.title" size="small" />
      </el-form-item>

      <el-form-item label="内容" prop="content">
        <Tinymce ref="editor" v-model="postForm.content" :height="300" />
      </el-form-item>

    </el-form>

    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">取 消</el-button>
      <el-button type="primary" @click="handleSave">确 定</el-button>
    </div>

  </el-dialog>


</template>

<script>
import { saveData, fetchDetail } from '@/api/sys/notice/notice'

export default {
  name: 'NoticeSaveDialog',
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    id: {
      type: String,
      default: ''
    }
  },

  data() {
    return {
      dialogVisible: false,
      loading: false,
      postForm: {
        id: '',
        title: '',
        content: ''
      },
      rules: {
        title: [
          { required: true, message: '公告标题不能为空！' }
        ],
        content: [
          { required: true, message: '公告内容不能为空！' }
        ]
      }
    }
  },

  watch: {
    // 检测查询变化
    visible: {
      handler() {
        this.dialogVisible = this.visible
        this.initData()
      }
    },
    // 检测查询变化
    id: {
      handler(val) {
        console.log('传入的ID为：', val)
        this.initData()
      }
    }
  },
  created() {
    this.dialogVisible = this.visible
  },
  methods: {

    // 初始化填充数据
    initData() {
      if (!this.id) {
        this.clearData()
      } else {
        this.preUpdate(this.id)
      }
    },

    preUpdate(id) {
      fetchDetail(id).then(res => {
        const data = res.data

        this.postForm.id = data.id
        this.postForm.title = data.title
        this.postForm.content = data.content
        // this.$refs.editor.setContent(this.postForm.content)
      })
    },

    handleSave() {
      this.$refs.postForm.validate((valid) => {
        if (!valid) {
          return
        }
        saveData(this.postForm).then(() => {
          this.$message({
            type: 'success',
            message: '公告保存成功!'
          })
          this.$emit('saved')
          this.handleClose()
        })
      })
    },

    handleClose() {
      this.dialogVisible = false
      this.$emit('update:visible', false)
      this.clearData()
    },

    clearData() {
      console.log('清理数据...', this.postForm)
      this.postForm.id = ''
      this.postForm.title = ''
      this.postForm.content = ''
      this.$refs.editor.reset()
      this.$nextTick(() => {
        this.$refs.postForm.clearValidate()
      })
    }
  }
}
</script>
